package com.lanou3g.musicenjoy.fragment;

import android.content.Intent;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.activities.HelloDrawerActivity;
import com.lanou3g.musicenjoy.activities.LoginActivity;
import com.lanou3g.musicenjoy.activities.SettingActivity;
import com.lanou3g.musicenjoy.adapter.MyPagerAdapter;
import com.lanou3g.musicenjoy.eventbus.MyEvent;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 辛鑫 on 15/10/24.
 * 我的,乐库,排行三个fragment的主fragment,相当于一个容器
 */
public class MainFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private TextView userName;

    private HelloDrawerActivity activity;

    private CircleImageView userImg;//头像

    @Bind(R.id.drawer_open)
    ImageView drawerOpen;
    @Bind(R.id.main_tablayout)
    TabLayout mainTablayout;
    @Bind(R.id.search)
    ImageView search;
    @Bind(R.id.title)
    LinearLayout title;
    @Bind(R.id.main_viewPager)
    ViewPager viewPager;
    @Bind(R.id.left_drawer)
    ListView drawerListivew;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    private ScanActivity scanFragment;
    private MyPagerAdapter adapter;
    private String[] mDrawerTitles;
    private List<Fragment> datas;
    private int[] imgs = {R.mipmap.icon_change_background,
             R.mipmap.icon_sleep_mode, R.mipmap.icon_preferences_dark, R.mipmap.icon_exit};
    private View headView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment, null);
        headView = inflater.inflate(R.layout.drawer_headview, null);
        ButterKnife.bind(this, view);
        Log.i("lanou", "---------");
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity= (HelloDrawerActivity) getActivity();

        Log.i("lanou", "---------70");
        adapter = new MyPagerAdapter(getFragmentManager());
        viewPager.setAdapter(adapter);
        drawerListivew.setOnItemClickListener(this);
        adapter.notifyDataSetChanged();
        mainTablayout.setupWithViewPager(viewPager);
        mainTablayout.setTabTextColors(getResources().getColor(R.color.colorMainTabNomal),
                getResources().getColor(R.color.colorMainTabSelected));
        mainTablayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorSelectedTabIndicatorColor));
        drawerOpen.setOnClickListener(this);
        search.setOnClickListener(this);
        mDrawerTitles = getResources().getStringArray(R.array.drawer_list_data);
        drawerListivew.addHeaderView(headView);
        drawerListivew.setAdapter(new SimpleAdapter(getActivity(), getData(), R.layout.drawer_list_item, new String[]{"img", "text"},
                new int[]{R.id.img, R.id.drawer_text}));

        userName = (TextView) getActivity().findViewById(R.id.user_name);
        userImg = (CircleImageView) getActivity().findViewById(R.id.user_img);
        userName.setOnClickListener(this);


        initData();

    }

    //qq登陆接收数据
    public void onEvent(MyEvent.Landing event) {
        userName.setText(event.getData().get("screen_name").toString());
        Picasso.with(getActivity()).load(event.getData().get("profile_image_url").toString()).into(userImg);


    }

    //微博登陆接收数据
    public void onEvent(MyEvent.weiboLanding event) {
        userName.setText(event.getInfo().get("screen_name").toString());
        Picasso.with(getActivity()).load(event.getInfo().get("profile_image_url").toString()).into(userImg);

    }

    //初始化数据方法
    private void initData() {
        datas = new ArrayList<Fragment>();
        datas.add(new MineFragment());
        datas.add(new Bankragment());
        datas.add(new FlippableStackViewFragment());
        datas.add(new RankingFragment());

        adapter.setData(datas);
    }

    //向抽屉中的行布局中添加行布局内容
    public List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < mDrawerTitles.length; i++) {
            Map<String, Object> map = new Hashtable<>();
            map.put("img", imgs[i]);
            map.put("text", mDrawerTitles[i]);
            list.add(map);
        }
        return list;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.drawer_open:
                drawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.search:
                getFragmentManager()
                        .beginTransaction()
                        .replace(R.id.container, new SearchingMainFragment())
                        .addToBackStack(null)
                        .commit();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        /**
         * Fragment是依附在Activity生存的,如果activity被销毁了,fragment就不存在了,commit方法就会报错
         * 所以在这个地方要判断一下,当fragment没有被销毁时再进行fragment的相关操作
         */
        if (!getActivity().isDestroyed()) {
            for (Fragment frag : datas) {
                getFragmentManager()
                        .beginTransaction()
                        .remove(frag)
                        .commit();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0://跳转登陆
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(intent, 67);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
//            case 4:
//                // scanFragment=new ScanActivity();
//                Intent intent1 = new Intent(getActivity(), ScanActivity.class);
//                startActivity(intent1);

              //  break;
            case 2://定时关机
                activity.showSleepDialog();

              break;
            case 3://设置
                Intent intentset = new Intent(getActivity(), SettingActivity.class);
                startActivity(intentset);
                break;
            case 4:
                activity.finish();
                break;
        }
    }

}
